package com.sky.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传，自动添加日期目录和UUID重命名
     *
     * @param bytes 原始文件字节
     * @param originalFilename 原始文件名（用于提取后缀）
     * @return 文件访问 URL
     */
    public String upload(byte[] bytes, String originalFilename) {
        // 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 构造日期目录
        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());

        // 提取文件后缀名（例如 .jpg）
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 构造唯一文件名
        String uuid = UUID.randomUUID().toString();
        String objectName = datePath + "/" + uuid + suffix;

        try {
            // 上传对象
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            System.out.println("OSSException: " + oe.getErrorMessage());
        } catch (ClientException ce) {
            System.out.println("ClientException: " + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        // 构建访问路径
        String domain = endpoint.replaceFirst("^https?://", "");
        String fileUrl = "https://" + bucketName + "." + domain + "/" + objectName;

        log.info("文件上传到:{}", fileUrl);

        return fileUrl;
    }
}
